#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import xlrd
import os
import xml.etree.ElementTree as ET


def _parseSheet2xml(sheet):
    print(sheet.name, sheet.nrows, sheet.ncols)
    fields = sheet.row_values(0)  # 第1行内容, 所有的字段名

    datas = []  # 所有的数据行
    [datas.append(_parseRow(fields, sheet, row)) for row in range(1, sheet.nrows)]
    return datas


def _parseRow(fields, sheet, row):
    data = {}
    for column in range(0, len(fields)):
        fieldName = fields[column]  # 取得当期列的字段名
        data[fieldName] = sheet.row(row)[column]
    return data


class Excel:

    def __init__(self, filename):
        self._filename = filename

    def parse2xml(self, sheets=[0]):
        filename = os.path.realpath(self._filename)
        excelFile = xlrd.open_workbook(filename)

        dates = []
        for sheetIndex in sheets:
            sheet = excelFile.sheet_by_index(sheetIndex)
            data = _parseSheet2xml(sheet)
            [dates.append(d) for d in data]
        return dates


def indent(elem, level=0):
    i = "\n" + level * "  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i


class XmlWriter:

    xmlOutputDir = 'output/'

    def __init__(self, filePreName):
        self._fileName = self.xmlOutputDir + filePreName.lower() + ".xml"

    def writeData2Xml(self, records):
        root = ET.Element('root')
        for r in records:
            recordTag = ET.Element('record', r.getFields())  # <record id='' ....>
            for var in r.getVecs():
                fieldTag = ET.SubElement(recordTag, var.getFieldName())  # <showAward>
                for value in var.getValues():
                    typeTag = ET.SubElement(fieldTag, var.getType())
                    typeTag.text = value
            root.append(recordTag)
        indent(root)  # 调用格式美化
        tree = ET.ElementTree(root)
        try:
            tree.write(self._fileName, 'utf-8')
        except EnvironmentError as err:
            print('write2Xml err:{0}'.format(err))
            return False
        return True
